import qiniu
from PIL import Image
import io
import uuid

QI_NIU_ACCESS_KEY = "sPkc5OTuyGj3WkW4Ms9Nm9_UL5AxAFyGtyaIti3a"
QI_NIU_SECRET_KEY = "YE3MKGyGKjPwQR-6veiagh5C01uphgvkXnhBQbSI"
QI_NIU_BUCKET_NAME = "wangliliang"


#  七牛云上传前先获取token
def Upfile():
    access_key = QI_NIU_ACCESS_KEY
    secret_key = QI_NIU_SECRET_KEY
    # 设置七牛空间(自己刚刚创建的)
    bucket_name = QI_NIU_BUCKET_NAME
    # 构建鉴权对象,授权
    q = qiniu.Auth(access_key, secret_key)
    # 生成token
    token = q.upload_token(bucket_name)
    # 返回token,key必须为uptoken
    return token


def Send_qiniu(img):
    _img = img.read()
    size = len(_img) / (1024 * 1024)
    image = Image.open(io.BytesIO(_img))

    key = str(uuid.uuid1()).replace("-", "")

    name = 'upfile.{0}'.format(image.format)  # 获取图片后缀（图片格式）
    if size > 1:
        # 压缩
        x, y = image.size
        im = image.resize((int(x / 1.73), int(y / 1.73)), Image.ANTIALIAS)  # 等比例压缩 1.73 倍
    else:
        # 不压缩
        im = image
    print()
    im.save('./' + name)  # 在根目录有个media文件
    path = './' + name

    token = Upfile()
    qiniu.put_file(token, key, path)
    url = 'http://q8cxk6j52.bkt.clouddn.com/{}'.format(key)
    return url